package com.gzkemays.demo.config.filter;

import com.gzkemays.demo.common.RedisCommon;
import com.gzkemays.demo.config.ReHttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

/**
 * @author gzkemays
 * @date 2021/3/18 17:13
 */
@Slf4j
@Component
public class ResourceInterceptor implements Filter {
  @Resource RedisTemplate redisTemplate;

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    String token = RedisCommon.getTokenByClient("gzkemays");
    HttpServletRequest httpReq = (HttpServletRequest) request;
    ReHttpServletRequest muReq = new ReHttpServletRequest(httpReq);
    log.info("获取头部 -> {}", muReq.getHeader("Authorization"));
    if (Objects.nonNull(token)) {
      muReq.putHeader("Authorization", token);
      log.info("插入头部 -> {}", token);
      log.info("获取头部2 -> {}", muReq.getHeader("Authorization"));
      chain.doFilter(muReq, response);
    }
    chain.doFilter(request, response);
  }
}
